package com.fowo.api.shein.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.aspect.BaseAspect;
import com.fowo.api.datainterface.constants.Constants;
import com.fowo.api.datainterface.constants.DataTypeKind;
import com.fowo.api.datainterface.entity.DatainterfaceAuthority;
import com.fowo.api.datainterface.service.DatainterfaceAuthorityService;
import com.fowo.api.datainterface.service.impl.DatainterfaceServiceImpl;
import com.fowo.api.datainterface.util.Common;
import com.fowo.api.entity.*;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformItemVo;
import com.fowo.api.model.shein.order.SheinOrderItemVo;
import com.fowo.api.model.shein.order.SheinOrderSearchParamPo;
import com.fowo.api.service.impl.*;
import com.fowo.api.shein.util.ApiSignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SheinOrderApiService {

    @Resource
    private DatainterfaceAuthorityService datainterfaceAuthorityBaseService;
    @Resource
    private Common common;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SheinOrderServiceImpl sheinOrderService;
    @Resource
    private SheinOrderGoodsServiceImpl sheinOrderGoodsService;
    @Resource
    private NavSellOrderServiceImpl navSellOrderService;
    @Resource
    private NavSellOrderPlatformServiceImpl navSellOrderPlatformService;
    @Resource
    private SysCountryServiceImpl sysCountryService;
    @Resource
    private ParilistServiceImpl parilistService;
    @Resource
    private DatainterfaceServiceImpl datainterfaceService;

    private static final String ORDER_LIST_URL = "/open-api/order/order-list";
    private static final String ORDER_DETAIL_URL = "/open-api/order/order-detail";
    private static final String ORDER_ADDRESS_URL = "/open-api/order/export-address";
    private static final String ORDER_CONFIRM_SHIPPING = "/open-api/order/confirm-shipping";

    public BaseAspect getBaseAspect() {
        return new BaseAspect(DataTypeKind.SHEIN.getValue());
    }

    /**
     * 同步订单
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncOrder() throws Exception {
        sheinOrderService.remove(null);
        sheinOrderGoodsService.remove(null);
        getOrderList();
        log.info("拉取订单数据完成");
        saveNavSellOrder();
        log.info("插入订单数据完成");

        navSellOrderService.splitTask();
        log.info("订单数据拆分检测完成");
        navSellOrderService.joinTask();
        log.info("订单数据合并检测完成");
    }
    public void getOrderList() throws Exception {

        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
                .eq(ShopInfo::getPlatform,"Shein")
                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));

        for(ShopInfo shop : list){
            Map<String,String> header = new HashMap<>();
            header.put("openKeyId",shop.getMarketplaceId());
            header.put("secretKey",shop.getRefreshToken());

            Map<String,Object> params = new HashMap<>();
            String startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(DateUtil.yesterday()));
            String endTime = DateUtil.formatDateTime(DateUtil.endOfDay(new Date()));
            int page = 1;
            int pageSize = 10;
            params.put("queryType",1);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            params.put("page",page);
            params.put("pageSize",pageSize);

            Object result = datainterfaceService.executeInterface(null, "EC00525", null, params, header);
            log.info("订单列表返回参数：{}",result.toString());
            JSONObject body = JSONUtil.parseObj(result);

            JSONObject resultObject = JSONUtil.parseObj(body);
            Integer code = resultObject.getInt("code");
            if(code == 0){
                JSONObject infoObject = resultObject.getJSONObject("info");
                Integer count = infoObject.getInt("count");
                JSONArray orderArray = infoObject.getJSONArray("orderList");
                List<String> orderNos = new ArrayList<>();
                for(int i = 0 ; i < orderArray.size() ; i++){
                    JSONObject orderObject = orderArray.getJSONObject(i);
                    orderNos.add(orderObject.getStr("orderNo"));
                }
                //检测订单号是否已经同步
                checkOrderNo(orderNos);

                // 拿到订单号 请求接口 获取定的那详情
                Map<String,Object> orderItems =  getOrderItem(shop.getId(),orderNos,header);
                List<SheinOrder> orderList = (List<SheinOrder>)orderItems.get("order");
                List<SheinOrderGoods> goodList =  (List<SheinOrderGoods>)orderItems.get("good");
                if(count > pageSize){
                    int pageNum = count / pageSize;
                    if (count % pageSize != 0) {
                        pageNum = pageNum + 1;
                    }
                    for (int i = 2; i <= pageNum; i++) {
                        params.put("page",i);
                        Map<String,Object> nextItems =  getNext(shop.getId(),params,header);
                        orderList.addAll((List<SheinOrder>)nextItems.get("order"));
                        goodList.addAll((List<SheinOrderGoods>)nextItems.get("good"));
                    }
                }
                sheinOrderService.saveBatch(orderList);
                sheinOrderGoodsService.saveBatch(goodList);
            }else{
                resultObject.getStr("msg");
                log.error("拉取SHEIN订单列表失败");
            }
        }
    }

    public Map<String,Object> getNext(Long sid,Map<String,Object> params,Map<String,String> header) throws Exception {

        Object result = datainterfaceService.executeInterface(null, "EC00525", null, params, header);
        JSONObject body = JSONUtil.parseObj(result);
        log.info("下一页订单列表返回参数：{}",JSONUtil.toJsonStr(body));
        JSONObject resultObject = JSONUtil.parseObj(body);
        Integer code = resultObject.getInt("code");
        if(code == 0){
            JSONObject infoObject = resultObject.getJSONObject("info");
            JSONArray orderArray = infoObject.getJSONArray("orderList");
            List<String> orderNos = new ArrayList<>();
            for(int i = 0 ; i < orderArray.size() ; i++){
                JSONObject orderObject = orderArray.getJSONObject(i);
                orderNos.add(orderObject.getStr("orderNo"));
            }
            //检测订单号是否已经同步
            checkOrderNo(orderNos);
            // 拿到订单号 请求接口 获取定的那详情
            return getOrderItem(sid,orderNos,header);
        }else{
            throw new Exception("拉取SHEIN订单列表失败");
        }
    }
    /**
     * 请求订单详情接口
     * @param orderNoList
     * @param header
     */
    public Map<String,Object> getOrderItem(Long sid,List<String> orderNoList,Map<String,String> header) throws Exception {
        Map<String,Object> result = new HashMap<>();
        List<SheinOrder> orderList = new ArrayList<>();
        List<SheinOrderGoods> goodList = new ArrayList<>();
        if(CollectionUtil.isEmpty(orderNoList)){
            result.put("order",orderList);
            result.put("good",goodList);
            return result;
        }

        Map<String,Object> params = new HashMap<>();
        params.put("orderNoList",orderNoList);

        Object response = datainterfaceService.executeInterface(null, "EC00526", null, params, header);
        JSONObject body = JSONUtil.parseObj(response);
        log.info("订单详情返回参数：{}",JSONUtil.toJsonStr(body));
        JSONObject resultObject = JSONUtil.parseObj(body);
        Integer code = resultObject.getInt("code");
        if(code == 0) {
            JSONArray infoArray = resultObject.getJSONArray("info");

            for(int i = 0 ; i < infoArray.size() ; i++){
                JSONObject infoObject = infoArray.getJSONObject(i);
                JSONArray orderGoodsInfoList = infoObject.getJSONArray("orderGoodsInfoList");
                JSONArray packageWaybillList = infoObject.getJSONArray("packageWaybillList");
                SheinOrder sheinOrder = JSONUtil.toBean(infoObject, SheinOrder.class);
                String packageIds = "";
                for(int j = 0 ; j < packageWaybillList.size() ; j++){
//                packages.getJSONObject(j).getStr("id");
                    packageIds = packageIds+packageWaybillList.getJSONObject(j).getStr("packageNo")+",";
                }
                sheinOrder.setPackageIds(packageIds.substring(0,packageIds.length()-1));
                sheinOrder.setSid(sid);
                getAddress(sheinOrder,header);
                orderList.add(sheinOrder);
                List<SheinOrderGoods> sheinOrderGoods = JSONUtil.toList(orderGoodsInfoList, SheinOrderGoods.class);
                sheinOrderGoods.stream().forEach(g -> g.setOrderNo(sheinOrder.getOrderNo()));
                goodList.addAll(sheinOrderGoods);
            }
            result.put("order",orderList);
            result.put("good",goodList);
            return result;
        }else{
            throw new Exception("获取订单详情失败");
        }
    }

    /**
     * 设置订单收货信息
     * @param sheinOrder
     * @param header
     * @throws Exception
     */
    public void getAddress(SheinOrder sheinOrder,Map<String,String> header) throws Exception {

        Map<String,Object> params = new HashMap<>();
        params.put("orderNo",sheinOrder.getOrderNo());
        params.put("handleType",1);

        Object response = datainterfaceService.executeInterface(null, "EC00527", null, params, header);
        JSONObject body = JSONUtil.parseObj(response);
        log.info("希音订单地址返回参数：{}",JSONUtil.toJsonStr(body));
        JSONObject resultObject = JSONUtil.parseObj(body);
        Integer code = resultObject.getInt("code");
        if(code == 0) {
            JSONObject infoObject = resultObject.getJSONObject("info");
            JSONArray receiveMsgList = infoObject.getJSONArray("receiveMsgList");
            JSONObject jsonObject = receiveMsgList.getJSONObject(0);
            setSheinOrderAddress(sheinOrder,jsonObject);
        }else {
            throw new Exception("获取订单详情失败");
        }
    }

    /**
     * 获取希音订单
     * @throws Exception
     */
//    public void getOrderList() throws Exception {
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Shein"), false);
//
//        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
//                .eq(ShopInfo::getPlatform,"Shein")
//                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
//
//        for(ShopInfo shop : list){
//            String openKeyId = shop.getMarketplaceId();
//            String secretKey = shop.getRefreshToken();
//            String timestamp = String.valueOf(new Date().getTime());
//            String signature = ApiSignUtil.getSign(openKeyId,ORDER_LIST_URL,secretKey,timestamp);
//
//            HttpHeaders header = new HttpHeaders();
//            header.set("Content-Type", "application/json;charset=UTF-8");
//            header.set("x-lt-openKeyId", openKeyId);
//            header.set("x-lt-timestamp", timestamp);
//            header.set("x-lt-signature", signature);
//
//            Map<String,Object> params = new HashMap<>();
//            String startTime = DateUtil.formatDateTime(DateUtil.beginOfDay(DateUtil.yesterday()));
//            String endTime = DateUtil.formatDateTime(DateUtil.endOfDay(new Date()));
//            int page = 1;
//            params.put("queryType",1);
//            params.put("startTime",startTime);
//            params.put("endTime",endTime);
//            params.put("page",page);
//            params.put("pageSize",30);
//
//            String url = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl")+ORDER_LIST_URL;
//            Object result = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//            log.info("订单列表返回参数：{}",result.toString());
//            JSONObject body = JSONUtil.parseObj(result);
//
//            JSONObject resultObject = JSONUtil.parseObj(body);
//            Integer code = resultObject.getInt("code");
//            if(code == 0){
//                JSONObject infoObject = resultObject.getJSONObject("info");
//                Integer count = infoObject.getInt("count");
//                JSONArray orderArray = infoObject.getJSONArray("orderList");
//                List<String> orderNos = new ArrayList<>();
//                for(int i = 0 ; i < orderArray.size() ; i++){
//                    JSONObject orderObject = orderArray.getJSONObject(i);
//                    orderNos.add(orderObject.getStr("orderNo"));
//                }
//                //检测订单号是否已经同步
//                checkOrderNo(orderNos);
//
//                // 拿到订单号 请求接口 获取定的那详情
//                Map<String,Object> orderItems =  getOrderItem(shop.getId(),orderNos,openKeyId,secretKey,entityAuthority);
//                List<SheinOrder> orderList = (List<SheinOrder>)orderItems.get("order");
//                List<SheinOrderGoods> goodList =  (List<SheinOrderGoods>)orderItems.get("good");
//                if(count > 30){
//                    int pageNum = count / 30;
//                    if (count % 30 != 0) {
//                        pageNum = pageNum + 1;
//                    }
//                    for (int i = 2; i <= pageNum; i++) {
//                        params.put("page",i);
//                        Map<String,Object> nextItems =  getNext(shop.getId(),openKeyId,secretKey,params,url,entityAuthority);
//                        orderList.addAll((List<SheinOrder>)nextItems.get("order"));
//                        goodList.addAll((List<SheinOrderGoods>)nextItems.get("good"));
//                    }
//                }
//                sheinOrderService.saveBatch(orderList);
//                sheinOrderGoodsService.saveBatch(goodList);
//            }else{
//                resultObject.getStr("msg");
//                log.error("拉取SHEIN订单列表失败");
//            }
//        }
//    }

    /**
     * 下一页
     * @param sid
     * @param openKeyId
     * @param params
     * @param url
     * @param entityAuthority
     * @return
     * @throws Exception
     */
//    public Map<String,Object> getNext(Long sid,String openKeyId,String secretKey,Map<String,Object> params,String url,DatainterfaceAuthority entityAuthority) throws Exception {
//        String timestamp = String.valueOf(new Date().getTime());
//        String signature = ApiSignUtil.getSign(openKeyId,ORDER_LIST_URL,secretKey,timestamp);
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json;charset=UTF-8");
//        header.set("x-lt-openKeyId", openKeyId);
//        header.set("x-lt-timestamp", timestamp);
//        header.set("x-lt-signature", signature);
//
//        Object result = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//        JSONObject body = JSONUtil.parseObj(result);
//        log.error("下一页订单列表返回参数：{}",JSONUtil.toJsonStr(body));
//        JSONObject resultObject = JSONUtil.parseObj(body);
//        Integer code = resultObject.getInt("code");
//        if(code == 0){
//            JSONObject infoObject = resultObject.getJSONObject("info");
//            JSONArray orderArray = infoObject.getJSONArray("orderList");
//            List<String> orderNos = new ArrayList<>();
//            for(int i = 0 ; i < orderArray.size() ; i++){
//                JSONObject orderObject = orderArray.getJSONObject(i);
//                orderNos.add(orderObject.getStr("orderNo"));
//            }
//            //检测订单号是否已经同步
//            checkOrderNo(orderNos);
//            // 拿到订单号 请求接口 获取定的那详情
//            return getOrderItem(sid,orderNos,openKeyId,secretKey,entityAuthority);
//        }else{
//            throw new Exception("拉取SHEIN订单列表失败");
//        }
//    }

    /**
     * 检查订单是否已经同步
     * @param orderNos
     */
    public void checkOrderNo(List<String> orderNos){
        final List<NavSellOrderPlatform> orderPlatforms = navSellOrderPlatformService.list(Wrappers.lambdaQuery(NavSellOrderPlatform.class)
                .eq(NavSellOrderPlatform::getPlatform, "Shein")
                .in(NavSellOrderPlatform::getPlatformOrderId, orderNos));
        final List<String> collect = orderNos.stream().filter(o -> orderPlatforms.stream().filter(p -> p.getPlatformOrderId().equals(o)).findAny().isPresent()).collect(Collectors.toList());
        orderNos.removeAll(collect);
    }

//    /**
//     * 请求订单详情接口
//     * @param orderNoList
//     * @param openKeyId
//     * @param entityAuthority
//     */
//    public Map<String,Object> getOrderItem(Long sid,List<String> orderNoList,String openKeyId,String secretKey,DatainterfaceAuthority entityAuthority) throws Exception {
//        Map<String,Object> result = new HashMap<>();
//        List<SheinOrder> orderList = new ArrayList<>();
//        List<SheinOrderGoods> goodList = new ArrayList<>();
//        if(CollectionUtil.isEmpty(orderNoList)){
//            result.put("order",orderList);
//            result.put("good",goodList);
//            return result;
//        }
//        String timestamp = String.valueOf(new Date().getTime());
//        String signature = ApiSignUtil.getSign(openKeyId,ORDER_DETAIL_URL,secretKey,timestamp);
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json;charset=UTF-8");
//        header.set("x-lt-openKeyId", openKeyId);
//        header.set("x-lt-timestamp", timestamp);
//        header.set("x-lt-signature", signature);
//
//        Map<String,Object> params = new HashMap<>();
//        params.put("orderNoList",orderNoList);
//
//        String url = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl")+ORDER_DETAIL_URL;
//        Object response = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//        JSONObject body = JSONUtil.parseObj(response);
//        log.info("订单详情返回参数：{}",JSONUtil.toJsonStr(body));
//        JSONObject resultObject = JSONUtil.parseObj(body);
//        Integer code = resultObject.getInt("code");
//        if(code == 0) {
//            JSONArray infoArray = resultObject.getJSONArray("info");
//
//            for(int i = 0 ; i < infoArray.size() ; i++){
//                JSONObject infoObject = infoArray.getJSONObject(i);
//                JSONArray orderGoodsInfoList = infoObject.getJSONArray("orderGoodsInfoList");
//                JSONArray packageWaybillList = infoObject.getJSONArray("packageWaybillList");
//                SheinOrder sheinOrder = JSONUtil.toBean(infoObject, SheinOrder.class);
//                String packageIds = "";
//                for(int j = 0 ; j < packageWaybillList.size() ; j++){
////                packages.getJSONObject(j).getStr("id");
//                    packageIds = packageIds+packageWaybillList.getJSONObject(j).getStr("packageNo")+",";
//                }
//                sheinOrder.setPackageIds(packageIds.substring(0,packageIds.length()-1));
//                sheinOrder.setSid(sid);
//                getAddress(sheinOrder,openKeyId,secretKey,entityAuthority);
//                orderList.add(sheinOrder);
//                List<SheinOrderGoods> sheinOrderGoods = JSONUtil.toList(orderGoodsInfoList, SheinOrderGoods.class);
//                sheinOrderGoods.stream().forEach(g -> g.setOrderNo(sheinOrder.getOrderNo()));
//                goodList.addAll(sheinOrderGoods);
//            }
//            result.put("order",orderList);
//            result.put("good",goodList);
//            return result;
//        }else{
//            throw new Exception("获取订单详情失败");
//        }
//    }
//
//    /**
//     * 设置订单收货信息
//     * @param sheinOrder
//     * @param openKeyId
//     * @param entityAuthority
//     * @throws Exception
//     */
//    public void getAddress(SheinOrder sheinOrder,String openKeyId,String secretKey,DatainterfaceAuthority entityAuthority) throws Exception {
//        String timestamp = String.valueOf(new Date().getTime());
//        String signature = ApiSignUtil.getSign(openKeyId,ORDER_ADDRESS_URL,secretKey,timestamp);
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json;charset=UTF-8");
//        header.set("x-lt-openKeyId", openKeyId);
//        header.set("x-lt-timestamp", timestamp);
//        header.set("x-lt-signature", signature);
//
//        Map<String,Object> params = new HashMap<>();
//        params.put("orderNo",sheinOrder.getOrderNo());
//        params.put("handleType",1);
//
//        String url = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl")+ORDER_ADDRESS_URL;
//        Object response = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//        JSONObject body = JSONUtil.parseObj(response);
//        log.error("订单地址返回参数：{}",JSONUtil.toJsonStr(body));
//        JSONObject resultObject = JSONUtil.parseObj(body);
//        Integer code = resultObject.getInt("code");
//        if(code == 0) {
//            JSONObject infoObject = resultObject.getJSONObject("info");
//            JSONArray receiveMsgList = infoObject.getJSONArray("receiveMsgList");
//            JSONObject jsonObject = receiveMsgList.getJSONObject(0);
//            setSheinOrderAddress(sheinOrder,jsonObject);
//        }else {
//            throw new Exception("获取订单详情失败");
//        }
//    }

    /**
     * 设置地址
     * @param sheinOrder
     * @param jsonObject
     */
    public void setSheinOrderAddress(SheinOrder sheinOrder,JSONObject jsonObject){
        sheinOrder.setLastName(jsonObject.getStr("lastName"));
        sheinOrder.setMiddleName(jsonObject.getStr("middleName"));
        sheinOrder.setFirstName(jsonObject.getStr("firstName"));
        sheinOrder.setCountry(jsonObject.getStr("country"));
        sheinOrder.setProvince(jsonObject.getStr("province"));
        sheinOrder.setCity(jsonObject.getStr("city"));
        sheinOrder.setDistrict(jsonObject.getStr("district"));
        sheinOrder.setStreet(jsonObject.getStr("street"));
        sheinOrder.setAddress(jsonObject.getStr("address"));
        sheinOrder.setAddressExt(jsonObject.getStr("addressExt"));
        sheinOrder.setPhone(jsonObject.getStr("phone"));
        sheinOrder.setPostCode(jsonObject.getStr("postCode"));
        sheinOrder.setTaxNo(jsonObject.getStr("taxNo"));
    }

    /**
     * 保存订单
     * @throws Exception
     */
//    @Transactional(rollbackFor = Exception.class)
    public void saveNavSellOrder() throws Exception {
        SheinOrderSearchParamPo search = new SheinOrderSearchParamPo();
        search.setDisableDataPremissions(true);
        final List<SheinOrderItemVo> orderItemVoList = sheinOrderService.search(search);
        for(SheinOrderItemVo order : orderItemVoList){
            NavSellOrder oldNavSellOrder = getNavSellOrderByPlatformOrderId(order.getOrderNo());
            if(null == oldNavSellOrder){
                NavSellOrderVo navSellOrder = buildNavSellOrder(order);
                navSellOrderService.create(navSellOrder);
            }
        }
    }

    /**
     * 根据平台单号获取订单
     * @param platformOrderId
     * @return
     */
    public NavSellOrder getNavSellOrderByPlatformOrderId(String platformOrderId) {
        NavSellOrderPlatform navSellOrderPlatform = navSellOrderPlatformService.getOne(Wrappers.lambdaQuery(NavSellOrderPlatform.class)
                .eq(NavSellOrderPlatform::getPlatformOrderId,platformOrderId)
                .eq(NavSellOrderPlatform::getPlatform,"Shein"));
        if(null == navSellOrderPlatform){
            return null;
        }
        NavSellOrder navSellOrder = navSellOrderService.getById(navSellOrderPlatform.getParentNavSellOrder());
        return navSellOrder;
    }

    /**
     * 构建订单管理数据
     * @param sheinOrder
     * @return
     */
    public NavSellOrderVo buildNavSellOrder(SheinOrderItemVo sheinOrder) {
        NavSellOrderVo navSellOrder = new NavSellOrderVo();

        final List<SheinOrderGoods> sheinOrderGoodsList = sheinOrderGoodsService.list(Wrappers.lambdaQuery(SheinOrderGoods.class).eq(SheinOrderGoods::getOrderNo, sheinOrder.getOrderNo()));
        final List<SysCountry> countries = sysCountryService.list(Wrappers.lambdaQuery(SysCountry.class).likeRight(SysCountry::getCountryCn, sheinOrder.getCountry()));
        // 基础信息
        navSellOrder.setShopInfo(sheinOrder.getSid());
        navSellOrder.setCurrency(sheinOrderGoodsList.get(0).getOrderCurrency());
        navSellOrder.setType(sheinOrderGoodsList.size() == 1?"1":"2"); // 1一件一单；2一件多单
        navSellOrder.setStatus("1");
//        navSellOrder.setSite(); //希音没有站点
        navSellOrder.setSplitType("1");
        navSellOrder.setPaymentWay("1");
        String buyerName = sheinOrder.getFirstName()+" "+sheinOrder.getLastName();
        if(StrUtil.isNotBlank(sheinOrder.getMiddleName())){
            buyerName = sheinOrder.getFirstName()+sheinOrder.getMiddleName()+sheinOrder.getLastName();
        }
        navSellOrder.setBuyerName(buyerName);
        navSellOrder.setDeliveryReceipt(buyerName);
        navSellOrder.setDeliveryZipCode(sheinOrder.getPostCode());
        navSellOrder.setDeliveryPhone(sheinOrder.getPhone());
        navSellOrder.setDeliveryCountry(CollectionUtil.isEmpty(countries)?null:countries.get(0).getId());
        navSellOrder.setDeliveryProvince(sheinOrder.getProvince());
        navSellOrder.setDeliveryCity(sheinOrder.getCity());
        navSellOrder.setDeliveryArea(sheinOrder.getDistrict());
        navSellOrder.setDeliveryAddressType("1");
        String address = sheinOrder.getAddress();
        if(StrUtil.isNotBlank(sheinOrder.getAddressExt())){
            address = address + " " + sheinOrder.getAddressExt();
        }
        navSellOrder.setDeliveryAddress1(address);
        if(StrUtil.isNotBlank(sheinOrder.getTaxNo())){
            navSellOrder.setDeliveryRecipientTaxType("5");
            navSellOrder.setDeliveryRecipientTaxNo(sheinOrder.getTaxNo());
        }
        navSellOrder.setDeliveryType("2");
        navSellOrder.setDeliveryCodeOrder(sheinOrder.getIsCod().equals("2")?"0":"1");
        // 平台信息
        NavSellOrderPlatformItemVo navSellOrderPlatform = new NavSellOrderPlatformItemVo();
        navSellOrderPlatform.setPlatformOrderId(sheinOrder.getOrderNo());
        navSellOrderPlatform.setCancelTime(sheinOrder.getOrderReturnTime());
        navSellOrderPlatform.setLatestShipTime(sheinOrder.getRequestDeliveryTime());
        navSellOrderPlatform.setSource("1");
        navSellOrderPlatform.setPaymentStatus("1");
        navSellOrderPlatform.setPaymentTime(sheinOrder.getPaymentTime());
        navSellOrderPlatform.setPlatform("Shein");
        navSellOrderPlatform.setPurchaseTime(sheinOrder.getOrderTime());
//        navSellOrderPlatform.setShippingStatus("");
//        navSellOrderPlatform.setStatus("");
        navSellOrderPlatform.setCountry(CollectionUtil.isEmpty(countries)?null:countries.get(0).getId());
        List<NavSellOrderPlatformItemVo> platformList = new ArrayList<>();
        platformList.add(navSellOrderPlatform);
        navSellOrder.setPlatform(platformList);

//        boolean isPari = true; //是否配对商品
        // 产品信息
        NavSellOrderDetailItemVo navSellOrderDetail;
        List<NavSellOrderDetailItemVo> sellOrderDetailList = new ArrayList<>();
        for(SheinOrderGoods orderGoods : sheinOrderGoodsList){
//            Parilist parilist = parilistService.getOne(Wrappers.lambdaQuery(Parilist.class)
//                    .eq(Parilist::getMsku,orderGoods.getSellerSku())
//                    .eq(Parilist::getShopId,sheinOrder.getSid())
//                    .eq(Parilist::getPlatforms,"Shein")
//                    .eq(Parilist::getType,"1"));

            navSellOrderDetail = new NavSellOrderDetailItemVo();
            navSellOrderDetail.setShopInfo(sheinOrder.getSid());
            navSellOrderDetail.setPlatformOrderId(orderGoods.getOrderNo());
            navSellOrderDetail.setItemFromName("1");
//            if(null == parilist){ // 没有匹配商品
//                isPari = false;
//            }else {
//                navSellOrderDetail.setImg(parilist.getImg());
//                navSellOrderDetail.setProductId(parilist.getProductId());
//                navSellOrderDetail.setProductIdName(parilist.getProductName());
//                navSellOrderDetail.setProductName(parilist.getProductName());
//                navSellOrderDetail.setSku(parilist.getSku());
//            }

            navSellOrderDetail.setGoodsTitle(orderGoods.getGoodsTitle());
            navSellOrderDetail.setGoodsCode(orderGoods.getSkuCode());
            navSellOrderDetail.setMsku(orderGoods.getSellerSku());
            String variantAttr = "";
            if(StrUtil.isNotBlank(orderGoods.getSkuAttribute())){
                List<String> attributeList = new ArrayList<>();
                final JSONArray attribute = JSONUtil.parseArray(orderGoods.getSkuAttribute());
                for(int i = 0 ; i < attribute.size() ; i++){
                    attributeList.add(attribute.getJSONObject(i).getStr("attrName"));
                }
                variantAttr = attributeList.stream().collect(Collectors.joining("/"));
            }
            navSellOrderDetail.setAttribute(variantAttr);
//            navSellOrderDetail.setSalesRevenueAmount();//销售收益
            navSellOrderDetail.setPrice(orderGoods.getSellerCurrencyPrice());
            navSellOrderDetail.setQuantity(1);
            navSellOrderDetail.setDiscount(orderGoods.getOrderCurrencyPromotionPrice());
            navSellOrderDetail.setAmount(orderGoods.getSellerCurrencyPrice());
            navSellOrderDetail.setTransactionCost(orderGoods.getCommission());
//            navSellOrderDetail.setOtherAmount(); // 平台其他费
            navSellOrderDetail.setSaleTax(orderGoods.getSaleTax());
            navSellOrderDetail.setPlatformStatus("1");

            sellOrderDetailList.add(navSellOrderDetail);
        }
        navSellOrder.setProduct(sellOrderDetailList);
//        if(!isPari){
//            navSellOrder.setTag(navSellOrderService.tagHandler(null,"4"));
//        }

        return navSellOrder;
    }

    /**
     * 预约发货接口
     * @param shopId
     * @param expressNos
     * @param orderNo
     */
    public JSONObject confirmShipping(Long shopId,List<String> expressNos,String orderNo){
        final ShopInfo shopInfo = shopInfoService.getById(shopId);
        Assert.isTrue(shopInfo.getPlatform().equals("Shein"),"店铺平台错误");
        Assert.isTrue(shopInfo.getSellerAuthStatus().equals("SQ01"),"店铺未授权");

        Map<String,String> header = new HashMap<>();
        header.put("openKeyId",shopInfo.getMarketplaceId());
        header.put("secretKey",shopInfo.getRefreshToken());

        Map<String,Object> params = new HashMap<>();
        params.put("expressNos",expressNos);
        params.put("orderNo",orderNo);

//        Object result = datainterfaceService.executeInterface(null, "EC00528", null, params, header);
//        JSONObject body = JSONUtil.parseObj(result);
//        JSONObject resultObject = JSONUtil.parseObj(body);
//        Integer code = resultObject.getInt("code");
//        Assert.isTrue(code == 0,resultObject.getStr("msg"));
        return JSONUtil.createObj();
    }
//    public JSONObject confirmShipping(Long shopId,List<String> expressNos,String orderNo){
//        final ShopInfo shopInfo = shopInfoService.getById(shopId);
//        Assert.isTrue(shopInfo.getPlatform().equals("Shein"),"店铺平台错误");
//        Assert.isTrue(shopInfo.getSellerAuthStatus().equals("SQ01"),"店铺未授权");
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Shein"), false);
//        String openKeyId = shopInfo.getMarketplaceId();
//        String secretKey = shopInfo.getRefreshToken();
//        String timestamp = String.valueOf(new Date().getTime());
//        String signature = ApiSignUtil.getSign(openKeyId,ORDER_CONFIRM_SHIPPING,secretKey,timestamp);
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json;charset=UTF-8");
//        header.set("x-lt-openKeyId", openKeyId);
//        header.set("x-lt-timestamp", timestamp);
//        header.set("x-lt-signature", signature);
//
//        Map<String,Object> params = new HashMap<>();
//        params.put("expressNos",expressNos);
//        params.put("orderNo",orderNo);
//
//        String url = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl")+ORDER_CONFIRM_SHIPPING;
//        Object result = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//        JSONObject body = JSONUtil.parseObj(result);
//        JSONObject resultObject = JSONUtil.parseObj(body);
//        Integer code = resultObject.getInt("code");
//        Assert.isTrue(code == 0,resultObject.getStr("msg"));
//        return JSONUtil.createObj();
//    }


//    public void getLabel(){
//        final List<ShopInfo> list = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class)
//                .eq(ShopInfo::getPlatform,"Shein")
//                .eq(ShopInfo::getSellerAuthStatus,"SQ01"));
//
//        final ShopInfo shopInfo = list.get(0);
//
//        DatainterfaceAuthority entityAuthority = datainterfaceAuthorityBaseService.getOne(Wrappers.<DatainterfaceAuthority>lambdaQuery().eq(DatainterfaceAuthority::getAppCode,"Shein"), false);
//        String openKeyId = shopInfo.getMarketplaceId();
//        String secretKey = shopInfo.getRefreshToken();
//        String timestamp = String.valueOf(new Date().getTime());
//        String signature = ApiSignUtil.getSign(openKeyId,"/open-api/order/print-express-info",secretKey,timestamp);
//
//        HttpHeaders header = new HttpHeaders();
//        header.set("Content-Type", "application/json;charset=UTF-8");
//        header.set("x-lt-openKeyId", openKeyId);
//        header.set("x-lt-timestamp", timestamp);
//        header.set("x-lt-signature", signature);
//
//        List<String> packageNo = List.of("GU2401312773486595");
//        Map<String,Object> params = new HashMap<>();
//        params.put("orderNo","GSUNF504T000WTR");
//        params.put("packageNo",JSONUtil.parseArray(packageNo));
//        String url = common.getAuthoritySimpleFactory(entityAuthority, "serverUrl")+"/open-api/order/print-express-info";
//        Object result = getBaseAspect().httpRequest(url, HttpMethod.POST, JSONUtil.toJsonStr(params), header, Object.class, Constants.Read, StrUtil.EMPTY);
//
//        System.out.println(result.toString());
//    }
}
